import {
  ProForm,
  ProFormDateTimePicker, ProFormDependency,
  ProFormInstance, ProFormSegmented,
  ProFormSelect,
  ProFormText,
  StepsForm,
} from '@ant-design/pro-components';
import {useModel} from '@umijs/max';
import {useRequest} from 'ahooks';
import {Alert, ConfigProvider, message} from 'antd';
import type {NamePath} from 'antd/lib/form/interface';
import {get} from 'lodash-es';
import {forwardRef, useEffect, useImperativeHandle, useRef} from 'react';

import QuillEditor from '@/components/QuillEditor';
import {createFileCollectionTask} from '@/services/administrative/file-collection';
import {getUserList} from '@/services/system/user-management';
import {FileCollectionProps} from '@/utils/types/administrative/file-collection';

type Props = {
  onClose: () => void;
  refreshList: () => void;
}

const CreationForm = forwardRef((props: Props, ref) => {
  const formRef = useRef<ProFormInstance>();

  useImperativeHandle(ref, () => ({
    submit() {
      return formRef.current?.getFieldsValue?.();
    },
    setFormValues(values) {
      formRef.current?.setFieldsValue(values);
    },
  }))
  /**
   * @description: 获取用户列表
   * @author: YoungYa
   */
  const {data: userList} = useRequest(async (params) => get(await getUserList(params), 'data.list', []), {
    defaultParams: [{current: 1, pageSize: 9999}],
  });
  // 获取全局状态
  const {initialState: {CurrentUser}} = useModel('@@initialState');

  useEffect(() => {
    console.log(CurrentUser);
  }, []);
  return (
    <ConfigProvider
      theme={{
        components: {
          Segmented: {
            itemSelectedBg: 'rgb(26,122,255)',
            itemSelectedColor: 'rgba(255,255,255,0.88)',
          },
        },
      }}
    >
      <StepsForm
        formRef={formRef}
        onFinish={async (values) => {
          try {
            const response = await createFileCollectionTask(values as FileCollectionProps)
            if (response.code === 200) {
              message.success('创建成功!');
              props.refreshList();
              props.onClose();
            }
          } catch (err) {
            message.error('创建失败!');
          }
        }}
      >
        <StepsForm.StepForm
          name={'task-info'}
          title={'任务信息'}
          style={{width: 600, paddingBottom: 80}}
        >
          {/* 标题 */}
          <ProFormText
            name="title"
            label="标题"
            placeholder="请输入任务标题"
            rules={[{required: true, message: '请输入任务标题!'}]}
          />
          {/* 要求描述 */}
          <ProForm.Item
            label="要求" name="content" rules={[{required: true, message: '请输入要求描述!'}]}
            tooltip={'文档描述支持富文本格式!'}>
            <QuillEditor height={300}/>
          </ProForm.Item>
        </StepsForm.StepForm>
        <StepsForm.StepForm
          name={'config'}
          title={'基本配置'}
          style={{minHeight: 500}}
        >
          {/* 文件类型 and 截止时间 */}
          <ProForm.Group>
            <ProFormSelect
              name="file_type"
              label="类型"
              tooltip={'文档类型支持多选!'}
              valueEnum={{
                all: '任意类型',
                image: '图片文件',
                word: 'Word 文档',
                excel: 'Excel 表格',
                pdf: 'PDF 文档',
                ppt: 'PPT 幻灯片',
                zip: 'ZIP 压缩包',
              }}
              mode={'multiple'} style={{width: 300}}
              rules={[{required: true, message: '请选择文档类型!'}]}
            />
            <ProFormDateTimePicker
              name="end_time" label="截止时间" tooltip={'收集任务的截止时间, 如果不设置则长期有效'}
            />
          </ProForm.Group>
          <ProForm.Group>
          {/* 访问权限 */}
          <ProFormSegmented
            name="access"
            label="访问权限"
            initialValue={'public'}
            options={['public', 'private', 'some']}
            valueEnum={{
              public: '公共',
              private: '私有',
              some: '指定人员',
            }}
          />
          {/* 是否置顶 */}
            <ProFormSegmented
              name="pinned"
              label="置顶"
              initialValue={'false'}
              options={['true', 'false']}
              valueEnum={{
                true: '是',
                false: '否',
              }}
            />
          </ProForm.Group>
          <ProFormDependency name={['access'] as NamePath[]}>
            {({access}) => {
              if (access === 'private') {
                return <ProFormText.Password
                  label="访问密码" name="access_pwd" allowClear initialValue={''}
                  rules={[{required: true, message: '请私有访问访问密码!'}]}
                />
              } else if (access === 'some') {
                return <ProFormSelect
                  name="submitter" label="指定人员"
                  mode={'multiple'}
                  options={userList?.map((u: API.USERMANAGEMENT) => ({label: u.cn_name, value: u.user_id})) || []}
                  fieldProps={{showSearch: true}}
                  rules={[{required: true, message: '请选择需提交材料的人员'}]}
                />
              }
              return <Alert
                message="公开访问权限"
                description="您选择的公开访问权限任何人员均可进行提交"
                type="info" showIcon
              />
            }}
          </ProFormDependency>
          {/* 审核人*/}
          <ProFormSelect
            name="reviewer_id" label="审核人"
            mode="single" initialValue={CurrentUser.user_id}
            options={userList?.map((u: API.USERMANAGEMENT) => ({label: u.cn_name, value: u.user_id})) || []}
            fieldProps={{showSearch: true}}
            rules={[{required: true, message: '请选择审核人'}]}
          />
        </StepsForm.StepForm>
      </StepsForm>
    </ConfigProvider>
  )
});

export default CreationForm;
